<template>
    <div>
        <!-- 控制按钮 -->
        <button @click="showIntercom">打开 Intercom 聊天窗口</button>
        <button @click="updateUserInfo">更新用户信息</button>
        <button @click="shutdownIntercom">关闭 Intercom</button>

        <!-- 模拟的 Intercom 聊天窗口 -->
        <div v-if="isChatOpen" class="intercom-mock-window">
            <div class="intercom-mock-header">
                <span>Intercom 客服聊天（模拟）</span>
                <button @click="isChatOpen = false" class="close-btn">×</button>
            </div>
            <div class="intercom-mock-body" ref="chatBody">
                <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.type">
                    {{ msg.text }}
                </div>
            </div>
            <div class="intercom-mock-footer">
                <input type="text" placeholder="输入消息..." v-model="inputMessage" @keyup.enter="sendMessage"
                    @focus="scrollToBottom" />
                <button @click="sendMessage">发送</button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, nextTick } from 'vue';

export default defineComponent({
    name: 'IntercomComponent',
    setup() {
        const isChatOpen = ref(false);
        const inputMessage = ref('');

        // 消息列表：每条消息包含文本和类型（sent/received）
        const messages = ref<Array<{ text: string; type: 'sent' | 'received' }>>([
            { text: '您好！这是模拟的 Intercom 聊天窗口。我们目前未连接真实服务。', type: 'received' },
            { text: '感谢支持，正在测试界面功能。', type: 'sent' },
            { text: '已收到，如有问题请留言。', type: 'received' },
        ]);

        // 用于自动滚动到底部
        const chatBody = ref<HTMLElement | null>(null);

        // 打开聊天窗口
        const showIntercom = () => {
            isChatOpen.value = true;
            console.log('[模拟] 打开 Intercom 聊天窗口 UI');
            nextTick(() => {
                scrollToBottom();
            });
        };

        // 更新用户信息（仅日志）
        const updateUserInfo = () => {
            console.log('[模拟] 更新用户信息', {
                userId: 1,
                name: 'Foo Bar',
                email: 'foo@bar.com',
            });
            alert('【模拟】用户信息已“更新”（未连接真实服务）');
        };

        // 关闭 Intercom（关闭窗口）
        const shutdownIntercom = () => {
            isChatOpen.value = false;
            console.log('[模拟] Intercom 已关闭');
            alert('【模拟】Intercom 服务已“关闭”');
        };

        // 发送消息
        const sendMessage = () => {
            const text = inputMessage.value.trim();
            if (!text) return;

            // 添加用户发送的消息
            messages.value.push({ text, type: 'sent' });
            inputMessage.value = '';

            // 滚动到底部
            scrollToBottom();

            // 模拟客服自动回复（延迟出现）
            setTimeout(() => {
                messages.value.push({
                    text: '这是模拟的自动回复：我们已收到您的消息，会尽快回复您。',
                    type: 'received',
                });
                scrollToBottom();
            }, 800);
        };

        // 滚动到底部的函数
        const scrollToBottom = () => {
            nextTick(() => {
                if (chatBody.value) {
                    chatBody.value.scrollTop = chatBody.value.scrollHeight;
                }
            });
        };

        return {
            showIntercom,
            updateUserInfo,
            shutdownIntercom,
            isChatOpen,
            inputMessage,
            messages,
            chatBody,
            sendMessage,
        };
    },
});
</script>

<style scoped>
button {
    margin: 8px;
    padding: 10px 16px;
    font-size: 14px;
    cursor: pointer;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
}

button:hover {
    background-color: #0056b3;
}

/* 模拟聊天窗口 */
.intercom-mock-window {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 350px;
    height: 450px;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    background-color: white;
    border: 1px solid #e0e0e0;
    display: flex;
    flex-direction: column;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    overflow: hidden;
    z-index: 9999;
}

.intercom-mock-header {
    background-color: #007bff;
    color: white;
    padding: 12px 16px;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.close-btn {
    background: none;
    border: none;
    color: white;
    font-size: 20px;
    cursor: pointer;
    width: 24px;
    height: 24px;
    line-height: 1;
    padding: 0;
}

.intercom-mock-body {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    background-color: #f9f9fb;
    display: flex;
    flex-direction: column;
    gap: 10px;
    font-size: 14px;
}

.message {
    max-width: 80%;
    padding: 8px 12px;
    border-radius: 18px;
    line-height: 1.4;
    word-wrap: break-word;
}

.message.received {
    align-self: flex-start;
    background-color: #e5e5ea;
    color: #000;
}

.message.sent {
    align-self: flex-end;
    background-color: #007bff;
    color: white;
}

.intercom-mock-footer {
    padding: 12px;
    background: white;
    border-top: 1px solid #eee;
    display: flex;
    gap: 8px;
}

.intercom-mock-footer input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 14px;
    outline: none;
}

.intercom-mock-footer input:focus {
    border-color: #007bff;
}

.intercom-mock-footer button {
    padding: 8px 12px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}

.intercom-mock-footer button:hover {
    background-color: #0056b3;
}
</style>